<template>
    <div class="login-container">
        <div class="login-box">
            <h1 class="login-title">登录</h1>
            <el-form :model="loginForm" ref="formRef" :rules="rules" label-width="80px" @keyup.enter="handleLogin">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button :loading="isLoading" type="primary" @click.prevent="handleLogin">
                        <span v-if="!isLoading">登录</span>
                        <span v-else>登录中... </span>
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import msgHelper from '@/util/msgHelper.js'
import useUserStore from '@/store/app/user'
const UserStore = useUserStore();
const router = useRouter();

const formRef = ref(null);
const loginForm = ref({
    username: '',
    password: ''
});

const rules = {
    username: [{ required: true, message: "请输入登录名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const handleLogin = () => {
    isLoading.value = true;
    try {
        formRef.value.validate((valid) => {
            if (valid) {
                UserStore.login(loginForm.value.username, loginForm.value.password)
                    .then( () => {
                        // UserStore.initLoginInfo().then(()=>
                        // {
                            msgHelper.show("登录成功")
                            router.push('/index');
                        // });
                    })
                    .catch(()=>{
                    })
                    .finally(() => {
                        isLoading.value = false;
                    });
                // 这里可以添加实际的登录逻辑，如发送请求到后端
            } else {
                msgHelper.showError("验证失败");
                isLoading.value = false;
                return false;
            }
        });
    } catch (error) {
        isLoading.value = false;
    }
};

const resetForm = () => {
    formRef.value.resetFields();
};
const isLoading = ref(false)
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
}

.login-box {
    width: 360px;
    padding: 40px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.login-title {
    margin-bottom: 30px;
    text-align: center;
    color: #333;
}
</style>